package com.bos.controller;

import com.bos.data.model.BosCustomerModel;
import com.bos.data.model.OAuthInfo;
import com.bos.service.WeiService;
import com.bos.util.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/*
 *
 * 这是一个跟微信对接的类
 *
 * */
@Controller
public class WeiXinController {
    @Autowired
    @Qualifier("weiServiceImpl")
    WeiService weiService;
    Logger logger=LoggerFactory.getLogger(WeiXinController.class);
    //用来发送模板和发送消息的方法
   /* @RequestMapping(value = "/getNews1")
    public String getAccessToken(HttpServletRequest request, HttpServletResponse response) throws Exception {
       Map<String, Object> map = new HashMap<String, Object>();
        Long nowTime = new Date().getTime();
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
        String APPID = WeiXinParamesUtil.APPID;
        String SECRET = WeiXinParamesUtil.SECRET;
        url = url.replace("APPID", APPID);
        url = url.replace("APPSECRET", SECRET);
        String content = HttpUtil.httpUrlConnect(url, null, "GET");
        map = HttpUtil.getAccessTokenByJsonStr(content);
        //接口AccessToken
        System.out.println(map.get("access_token"));
        String accessToken = (String) map.get("access_token");
        int expiresIn = (int) map.get("expires_in");
        System.out.println(accessToken + "----" + expiresIn);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date date = new Date();
        String saveDate = sdf.format(date);
        List<AccessTokenModel> accessTokens = weiService.findAccessToken("weixin");
        // 如果没有AccessToken的话
        AccessTokenModel acc = null;
        if (accessTokens.size() <= 0) {
            // 首先要查询到accessToken(第一次查询的话，将accessToken保存到数据库中)
            AccessTokenModel access = new AccessTokenModel(accessToken, expiresIn, saveDate, "weixin");
            int row = weiService.insertAccessToken(access);
            if (row > 0) {
                System.out.println("增加成功");
            }
            return "redirect:toIndex";
        } else {
            acc = accessTokens.get(0);
            String saveTime = acc.getSaveDate();
            long time = sdf.parse(saveTime).getTime();
            long now = new Date().getTime();
            long interval = (now - time) / 1000;
            if (interval > 7000) {// 超过7000秒，重新获取accessToken

                // 更新数据库
                String newDate = sdf.format(new Date());
                acc.setSaveDate(saveDate);
                acc.setToken(accessToken);
                acc.setExpiresIn(Integer.parseInt(String
                        .valueOf(interval)));
                acc.setType("weixin");
                int row1 = weiService.updateByExpirIn(acc);
                //第二步：获取微信code(wx39b1bb2c2b663946)
                String code = GetWeiXinCode.getCodeRequest();
                System.out.println("controller中为：" + code);

                //第三步，通过code去获取网页授权AccessToken

                //第四步，通过code 拿到用户的openid
                String openId=GetOpenid.getOpenid("wx39b1bb2c2b663946");
                //System.out.println(openId+"-----");

                PrintWriter out = response.getWriter();
                //后面加上用来回复消息
                try {
                    String respMessage = WechatService.weixinPost(request);
                    System.out.println("回复的消息为：" + respMessage);
                    out.write(respMessage);
                    out.print(respMessage); // 将回应发送给微信服务器
                } catch (Exception e) {
                    System.out.println("抛出异常");
                    e.printStackTrace();
                }


            }
            return "redirect:toIndex";
        }

    }
*/


    @RequestMapping(value = "/getNews")
    public String getNews(){
        String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
        String REDIRECT_URI = "http://hgbcbim.oicp.io/getOpenId";//你的回调页
        url = url.replace("APPID",WeiXinParamesUtil.APPID);
        url = url.replace("STATE", "test");
        url = url.replace("REDIRECT_URI", REDIRECT_URI);
        return "redirect:"+url;
    }

    public static String OPENID;
    @RequestMapping(value = "/getOpenId")
    public String callBack(ModelMap modelMap, HttpServletRequest req, HttpServletResponse response) throws Exception {
        String code = req.getParameter("code");
        OAuthInfo oat = GetOpenid.getOAuthOpenId(WeiXinParamesUtil.APPID, WeiXinParamesUtil.SECRET, code);
        String openId=oat.getOpenId();
        OPENID=openId;
        //在这里查询出客户表中的openid是否存在
        BosCustomerModel customer=weiService.findBosCustomerModelByOpenId(openId);
        if(customer!=null) {
            return "sucess";
        }
        return "findName";

    }
    @RequestMapping(value="/insertData",method = RequestMethod.POST)
    public String insertCustomer(@RequestParam("cname") String cname){
        //第一次输入的时候将名字和openId保存到客户表中
        weiService.insertCustomer(WeiXinController.OPENID,cname);
        //如果是第二次点微信授权，则可以不用输入姓名

        return "sucess";
    }




    //2.订阅号之与微信公众平台
    //这是用来接收微信消息和事件的接口URL（方法）
    //http://bos.shgae.cn/mis/getNews
    //1.获取接口Access_Token 用来创建自定义菜单（验证token）
    //参考网址：https://www.cnblogs.com/oushiyang/p/7724445.html
	/*@RequestMapping(value="/getNews")
		public @ResponseBody
    String getNews(HttpServletRequest request, HttpServletResponse response) throws Exception{

	        //微信加密签名，signature结合了开发者填写的token参数和请求中的timestamp，nonce参数
	        String signature = request.getParameter("signature");
	        //时间戳
	        String timestamp = request.getParameter("timestamp");
	        //随机数
	        String nonce = request.getParameter("nonce");
	        //随机字符串
	        String echostr = request.getParameter("echostr");
	        System.out.println(signature+"-----"+timestamp+"-----"+""+nonce);
	        String method=request.getMethod();
	        if("GET".equals(method)){

	        if (SignUtil.checkSignature(signature, timestamp, nonce)) {
	            logger.info("[signature: "+signature + "]<-->[timestamp: "+ timestamp+"]<-->[nonce: "+nonce+"]<-->[echostr: "+echostr+"]");
	            response.getOutputStream().println(echostr);
	            System.out.println("微信验证成功");
	          *//*  Map<String, Object> map=WeiXinUtil.getAccessToken()
	            System.out.println(map.get("access_token"));*//*
	            return echostr;
	        }
	        return "";
	        }if("POST".equals(method)){
	        	System.out.println("请求方式"+method);
	        	//调用核心业务类接收消息，处理消息
	        }
		return "";
	   }
*/
}
